﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using DevExpress.XtraEditors;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Grid;
using DevExpress.XtraGrid.Views.Grid.ViewInfo;
using DevExpress.XtraGrid.Columns;
using DevExpress.XtraGrid.Views.Base;
using Model;

namespace TanHungLong
{
    public partial class FrmBangLuong : DevExpress.XtraEditors.XtraForm
    {
        #region variant
        private FormStatus formStatus = FormStatus.View;
        private bool allowCloseForm = true;
        private ThangTinhLuongBOCollection thangTinhLuongBOCollection = null;
        private BangLuongBOCollection bangLuongBOCollection = null;
        private ThayDoiChucVuReduceBOCollection thayDoiChucVuBOCollection = null;
        private ThayDoiLuongReduceBOCollection thayDoiLuongBOCollection = null;
        private KhoanPhuCapReduceBOCollection phuCapBOCollection = null;
        private TamUngLuongReduceBOCollection tamUngBOCollection = null;

        private string COLUMN_FIRST = "ThuNhapKhac";
        private string COLUMN_SECOND = "Khac";
        #endregion variant

        //=====================================
        #region form
        public FrmBangLuong()
        {
            InitializeComponent();

            this.Load += new EventHandler(FrmBangLuong_Load);
            this.FormClosing += new FormClosingEventHandler(FrmBangLuong_FormClosing);

            this.btnRefresh.Click += new EventHandler(btnRefresh_Click);
            this.btnSave.Click += new EventHandler(btnSave_Click);
            this.btnCancel.Click += new EventHandler(btnCancel_Click);
            this.btnClose.Click += new EventHandler(btnClose_Click);
            this.btnAdd.Click += new EventHandler(btnAdd_Click);
            this.btnPrint.Click += new EventHandler(btnPrint_Click);
            this.btnLock.Click += new EventHandler(btnLock_Click);
            this.btnUnlock.Click += new EventHandler(btnUnlock_Click);
            this.btnCalc.Click += new EventHandler(btnCalc_Click);

            this.grdView.RowCellStyle += new RowCellStyleEventHandler(grdView_RowCellStyle);
            this.grdView.CustomDrawGroupRow += new RowObjectCustomDrawEventHandler(grdView_CustomDrawGroupRow);
        }

        private void FrmBangLuong_Load(object sender, EventArgs e)
        {
            MyStyle.SetGridStyle(this.grdViewThang, false);

            Utility.InitControl(this.repLookUpPhongBanID);

            this.numNam.Value = DateTime.Now.Year;

            RefreshData();
            SetFormStatus(this.formStatus);

            this.numNam.EditValueChanged += new EventHandler(numNam_EditValueChanged);
            this.grdViewThang.FocusedRowChanged += new FocusedRowChangedEventHandler(grdViewThang_FocusedRowChanged);
            this.grdView.CellValueChanged += new CellValueChangedEventHandler(grdView_CellValueChanged);
        }

        private void FrmBangLuong_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (this.allowCloseForm == false)
                e.Cancel = true;
        }
        #endregion form

        //=====================================
        #region control
        private void numNam_EditValueChanged(object sender, EventArgs e)
        {
            FilterNam();
        }
        #endregion control

        //=====================================
        #region button
        private void btnCalc_Click(object sender, EventArgs e)
        {
            Calc();
        }

        private void btnUnlock_Click(object sender, EventArgs e)
        {
            UnLock();
        }

        private void btnLock_Click(object sender, EventArgs e)
        {
            Lock();
        }

        private void btnPrint_Click(object sender, EventArgs e)
        {
            Print();
        }

        private void btnAdd_Click(object sender, EventArgs e)
        {
            Add();
        }

        private void btnRefresh_Click(object sender, EventArgs e)
        {
            RefreshData();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            Save();
        }

        private void btnCancel_Click(object sender, EventArgs e)
        {
            Cancel();
        }

        private void btnClose_Click(object sender, EventArgs e)
        {
            this.Close();
        }
        #endregion button

        //=====================================
        #region grid
        private void grdView_CellValueChanged(object sender, CellValueChangedEventArgs e)
        {
            if (this.formStatus == FormStatus.Edit)
            {
                string fieldName = e.Column.FieldName;
                double Luong = 0;
                double PhuCap = 0;
                double ThuNhapKhac = 0;
                double Tong = 0;
                double TamUng = 0;
                double BHXH = 0;
                double BHYT = 0;
                double BHTN = 0;
                double Khac = 0;
                double ThucNhan = 0;

                if (fieldName == "ThuNhapKhac")
                {
                    Luong = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "Luong"), 0);
                    PhuCap = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "PhuCap"), 0);
                    ThuNhapKhac = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "ThuNhapKhac"), 0);
                    Tong = Luong + PhuCap + ThuNhapKhac;

                    this.grdView.SetRowCellValue(e.RowHandle, "Tong", Tong);
                }
                else
                    if (fieldName == "Khac" || fieldName == "Tong")
                    {
                        Tong = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "Tong"), 0);
                        TamUng = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "TamUng"), 0);
                        BHXH = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "BHXH"), 0);
                        BHYT = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "BHYT"), 0);
                        BHTN = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "BHTN"), 0);
                        Khac = StaticUtil.GetDouble(this.grdView.GetRowCellValue(e.RowHandle, "Khac"), 0);
                        ThucNhan = Tong - (TamUng + BHXH + BHYT + BHTN + Khac);

                        this.grdView.SetRowCellValue(e.RowHandle, "ThucNhan", ThucNhan);
                    }
            }
        }

        private void grdViewThang_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {
            FilterThangTinhLuongID();
        }

        private void grdView_CustomDrawGroupRow(object sender, RowObjectCustomDrawEventArgs e)
        {
            //GridGroupRowInfo info = e.Info as GridGroupRowInfo;
            //int rowHandle = this.grdViewNhanVien.GetDataRowHandleByGroupRowHandle(info.RowHandle);

            //if (info.Column.FieldName == "PhongBanID")
            //{
            //    if (StaticUtil.GetInt(info.EditValue) < int.MaxValue - 1)
            //    {
            //        if (info.EditValue.ToString() != "")
            //        {
            //            tenChiNhanh = this.chiNhanhBOCollection.GetChiNhanhBO((int)info.EditValue).TenChiNhanh;
            //            info.GroupText = tenChiNhanh + " (" + sumText + ")";
            //        }
            //    }
            //    else
            //        if (StaticUtil.GetInt(info.EditValue) == int.MaxValue)
            //            info.GroupText = "Nhân viên mới";
            //        else
            //            info.GroupText = "Chưa có chi nhánh" + " (" + sumText + ")";
            //}
        }

        private void grdView_RowCellStyle(object sender, RowCellStyleEventArgs e)
        {
        }
        #endregion grid

        //=====================================
        #region function
        private void RefreshData()
        {
            PhongBanBOList phongBanBOList = PhongBanBOList.GetPhongBanBOList();
            Utility.SetData(this.repLookUpPhongBanID, phongBanBOList, phongBanBOList.Count);

            this.thayDoiChucVuBOCollection = ThayDoiChucVuReduceBOCollection.GetThayDoiChucVuReduceBOCollection("", "NhanVienID,NgayApDung");
            this.thayDoiLuongBOCollection = ThayDoiLuongReduceBOCollection.GetThayDoiLuongReduceBOCollection("", "NhanVienID,NgayApDung");
            this.phuCapBOCollection = KhoanPhuCapReduceBOCollection.GetKhoanPhuCapReduceBOCollection("", "NhanVienID,NgayApDung");
            this.tamUngBOCollection = TamUngLuongReduceBOCollection.GetTamUngLuongReduceBOCollection("", "NhanVienID,Ngay");

            if (this.bangLuongBOCollection != null)
                this.bangLuongBOCollection.nhanVienBOCollection = NhanVienReduceBOCollection.GetNhanVienReduceBOCollection();

            FilterNam();
        }

        private void FilterNam()
        {
            int nam = decimal.ToInt32(this.numNam.Value);
            this.thangTinhLuongBOCollection = ThangTinhLuongBOCollection.GetThangTinhLuongBOCollection("Nam=" + nam, "Thang");
            this.bangLuongBOCollection = BangLuongBOCollection.GetBangLuongBOCollection("Nam=" + nam);

            int i = 0;
            int length = this.thangTinhLuongBOCollection.Count;

            Hashtable hstThang = new Hashtable();
            for (i = 0; i < length; i++)
                hstThang.Add(this.thangTinhLuongBOCollection[i].Thang.Value, true);

            for (i = 1; i <= 12; i++)
            {
                if (hstThang.ContainsKey(i) == false)
                {
                    ThangTinhLuongBO thangTinhLuongBO = ThangTinhLuongBOCollection.NewThangTinhLuongBO();
                    thangTinhLuongBO.Thang = i;
                    thangTinhLuongBO.Nam = nam;
                    thangTinhLuongBO.Ten = "Tháng " + i + " - " + nam;
                    this.thangTinhLuongBOCollection.Add(thangTinhLuongBO);
                }
            }

            this.bdSourceThangTinhLuong.DataSource = this.thangTinhLuongBOCollection;
            this.bdSource.DataSource = this.bangLuongBOCollection.Clone();

            FilterThangTinhLuongID();
        }

        private void FilterThangTinhLuongID()
        {
            int? ThangTinhLuongID = StaticUtil.GetRealInt(this.grdViewThang.GetFocusedRowCellValue("ThangTinhLuongID"));
            if (ThangTinhLuongID != null)
            {
                bool Khoa = StaticUtil.GetBool(this.grdViewThang.GetFocusedRowCellValue("Khoa"));
                this.grdView.ActiveFilterString = "ThangTinhLuongID=" + ThangTinhLuongID.Value.ToString();

                bool isNew = (ThangTinhLuongID.Value < 0);
                this.btnAdd.Visible = isNew;
                this.btnCalc.Visible = !isNew;
                this.btnPrint.Visible = !isNew;
                this.btnLock.Visible = (!isNew && !Khoa);
                this.btnUnlock.Visible = (!isNew && Khoa);

                this.grdView.CheckLoaded();
                SetStt();
            }
        }

        private void Add()
        {
            int nam = decimal.ToInt32(this.numNam.Value);
            int? ThangTinhLuongID = StaticUtil.GetRealInt(this.grdViewThang.GetFocusedRowCellValue("ThangTinhLuongID"));

            if (ThangTinhLuongID != null)
            {
                Calc();
                FilterThangTinhLuongID();
            }
        }

        private void Calc()
        {
            int nam = decimal.ToInt32(this.numNam.Value);
            int thang = StaticUtil.GetInt(this.grdViewThang.GetFocusedRowCellValue("Thang"), -1);
            int? ThangTinhLuongID = StaticUtil.GetRealInt(this.grdViewThang.GetFocusedRowCellValue("ThangTinhLuongID"));

            if (ThangTinhLuongID != null)
            {
                this.bdSource.EndEdit();
                BangLuongBOCollection tmpBangLuongBOCollection = (BangLuongBOCollection)this.bdSource.DataSource;

                int iCompare = nam * 10000 + thang * 100 + (int)Session.thietDatBOCollection.GetDoubleValue(LoaiThietDat.NgayTinhLuong);
                int i = 0;
                int j = 0;
                int length = this.bangLuongBOCollection.nhanVienBOCollection.Count;
                int lengthJ = 0;
                NhanVienReduceBO nhanVienBO = null;
                ThayDoiChucVuReduceBO chucVuBO = null;
                ThayDoiLuongReduceBO luongBO = null;
                KhoanPhuCapReduceBOCollection tmpPhuCapReduceBOCollection = null;
                bool valid = true;
                int TinhTrangCongViec = 0;
                double PhuCap = 0;
                double Tong = 0;
                double TamUng = 0;
                double BHXH = 0;
                double BHYT = 0;
                double BHTN = 0;

                double PT_BHXH = StaticUtil.GetDouble(Session.thietDatBOCollection.GetDoubleValue(LoaiThietDat.BHXH), 0) / 100.0;
                double PT_BHYT = StaticUtil.GetDouble(Session.thietDatBOCollection.GetDoubleValue(LoaiThietDat.BHYT), 0) / 100.0;
                double PT_BHTN = StaticUtil.GetDouble(Session.thietDatBOCollection.GetDoubleValue(LoaiThietDat.BHTN), 0) / 100.0;
                double LuongBHXH = 0;

                for (i = 0; i < length; i++)
                {
                    nhanVienBO = this.bangLuongBOCollection.nhanVienBOCollection[i];

                    //nhân viên còn đang làm việc hay đã nghỉ việc
                    valid = true;
                    TinhTrangCongViec = StaticUtil.GetInt(nhanVienBO.TinhTrangCongViecID, 100);
                    if (TinhTrangCongViec > 1)
                    {
                        if (nhanVienBO.NgayKetThucLamViec == null)
                            valid = false;
                        else
                            if (StaticUtil.GetIntFromDT(nhanVienBO.NgayKetThucLamViec) < iCompare)
                                valid = false;
                    }


                    if (valid) //nhân viên có làm việc trong thời gian đó
                    {
                        luongBO = this.thayDoiLuongBOCollection.GetThayDoiLuongReduceBO(nhanVienBO.NhanVienID.Value, thang, nam);
                        if (luongBO != null)
                        {
                            chucVuBO = this.thayDoiChucVuBOCollection.GetThayDoiChucVuReduceBO(nhanVienBO.NhanVienID.Value, thang, nam);
                            if (chucVuBO != null)
                            {
                                BangLuongBO bangLuongBO = BangLuongBOCollection.NewBangLuongBO();
                                bangLuongBO.MaNhanVien = nhanVienBO.MaNhanVien;
                                bangLuongBO.Ho = nhanVienBO.Ho;
                                bangLuongBO.Ten = nhanVienBO.Ten;
                                bangLuongBO.Nu = nhanVienBO.Nu;
                                bangLuongBO.ThangTinhLuongID = ThangTinhLuongID;
                                bangLuongBO.Nam = nam;
                                bangLuongBO.NhanVienID = nhanVienBO.NhanVienID;
                                bangLuongBO.PhongBanID = chucVuBO.PhongBanID;
                                bangLuongBO.ChucVuID = chucVuBO.ChucVuID;
                                bangLuongBO.Luong = luongBO.ThanhTien;

                                tmpPhuCapReduceBOCollection = this.phuCapBOCollection.FilterData(nhanVienBO.NhanVienID.Value, thang, nam);
                                PhuCap = 0;
                                lengthJ = tmpPhuCapReduceBOCollection.Count;
                                for (j = 0; j < lengthJ; j++)
                                    PhuCap += StaticUtil.GetDouble(tmpPhuCapReduceBOCollection[j].SoTien, 0);

                                bangLuongBO.PhuCap = PhuCap;

                                Tong = StaticUtil.GetDouble(bangLuongBO.Luong, 0) + PhuCap;
                                bangLuongBO.Tong = Tong;

                                TamUng = this.tamUngBOCollection.GetTamUng(nhanVienBO.NhanVienID.Value, thang, nam);
                                bangLuongBO.TamUng = TamUng;

                                LuongBHXH = StaticUtil.GetDouble(nhanVienBO.LuongBHXH, 0);

                                BHXH = (StaticUtil.GetBool(nhanVienBO.BHXH) ? PT_BHXH * LuongBHXH : 0);
                                bangLuongBO.BHXH = BHXH;

                                BHYT = (StaticUtil.GetBool(nhanVienBO.BHYT) ? PT_BHYT * LuongBHXH : 0);
                                bangLuongBO.BHYT = BHYT;

                                BHTN = (StaticUtil.GetBool(nhanVienBO.BHTN) ? PT_BHTN * LuongBHXH : 0);
                                bangLuongBO.BHTN = BHTN;

                                bangLuongBO.ThucNhan = Tong - (TamUng + BHXH + BHYT + BHTN);

                                tmpBangLuongBOCollection.Add(bangLuongBO);
                            }
                        }
                    }
                }

                this.bdSource.DataSource = tmpBangLuongBOCollection;

                this.formStatus = FormStatus.Edit;
                SetFormStatus(this.formStatus);
                Session.CloseIndex++;
            }
        }

        private void Save()
        {
            int nam = decimal.ToInt32(this.numNam.Value);
            int? ThangTinhLuongID = StaticUtil.GetRealInt(this.grdViewThang.GetFocusedRowCellValue("ThangTinhLuongID"));
            if (ThangTinhLuongID != null)
            {
                string oldColumn = this.grdView.FocusedColumn.FieldName;
                string newColumn = (oldColumn == this.COLUMN_FIRST ? this.COLUMN_SECOND : this.COLUMN_FIRST);
                this.grdView.FocusedColumn = this.grdView.Columns[newColumn];

                this.bdSource.EndEdit();

                this.bangLuongBOCollection = (BangLuongBOCollection)this.bdSource.DataSource;

                ThangTinhLuongBO thangTinhLuongBO = null;
                if (ThangTinhLuongID < 0)
                {
                    thangTinhLuongBO = ThangTinhLuongBO.NewRootThangTinhLuongBO();
                    thangTinhLuongBO.Thang = StaticUtil.GetInt(this.grdViewThang.GetFocusedRowCellValue("Thang"), -1);
                    thangTinhLuongBO.Nam = StaticUtil.GetInt(this.grdViewThang.GetFocusedRowCellValue("Nam"), -1);
                    thangTinhLuongBO.Ten = (string)this.grdViewThang.GetFocusedRowCellValue("Ten");
                    thangTinhLuongBO = thangTinhLuongBO.Save();
                    this.grdViewThang.SetFocusedRowCellValue("ThangTinhLuongID", thangTinhLuongBO.ThangTinhLuongID);
                }
                else
                {
                    thangTinhLuongBO = this.thangTinhLuongBOCollection.GetThangTinhLuongBO(ThangTinhLuongID.Value);
                    thangTinhLuongBO.Khoa = true;
                    thangTinhLuongBO = thangTinhLuongBO.Save();
                    this.grdViewThang.SetFocusedRowCellValue("Khoa", thangTinhLuongBO.Khoa.Value);
                }

                if (ThangTinhLuongID < 0)
                {
                    int length = this.bangLuongBOCollection.Count;
                    for (int i = 0; i < length; i++)
                        if (this.bangLuongBOCollection[i].ThangTinhLuongID.Value == ThangTinhLuongID.Value)
                            this.bangLuongBOCollection[i].ThangTinhLuongID = thangTinhLuongBO.ThangTinhLuongID;
                }

                this.bangLuongBOCollection = this.bangLuongBOCollection.Save();
                this.bdSource.DataSource = this.bangLuongBOCollection.Clone();

                this.grdView.FocusedColumn = this.grdView.Columns[oldColumn];

                this.formStatus = FormStatus.View;
                SetFormStatus(this.formStatus);
                Session.CloseIndex--;

                FilterThangTinhLuongID();
            }
        }

        private void Cancel()
        {
            this.formStatus = FormStatus.View;
            SetFormStatus(this.formStatus);
            Session.CloseIndex--;

            this.bdSource.DataSource = this.bangLuongBOCollection.Clone();
            FilterThangTinhLuongID();
        }

        private void Print()
        {
        }

        private void Lock()
        {
        }

        private void UnLock()
        {
        }

        private void SetFormStatus(FormStatus formStatus)
        {
            bool edit = (formStatus != FormStatus.View);
            this.allowCloseForm = !edit;

            MyStyle.SetGridStyle(this.grdView, edit);

            this.numNam.Enabled = !edit;
            this.grdControlThang.Enabled = !edit;
            this.btnLock.Visible = !edit;
            this.btnUnlock.Visible = !edit;
            this.btnPrint.Visible = !edit;
            this.btnClose.Visible = !edit;
            this.btnRefresh.Visible = !edit;

            this.btnSave.Visible = edit;
            this.btnCancel.Visible = edit;

            foreach (GridColumn col in this.grdView.Columns)
            {
                if (col.Visible)
                {
                    if (col.FieldName == "ThuNhapKhac" || col.FieldName == "Khac")
                        col.OptionsColumn.AllowEdit = edit;
                    else
                        col.OptionsColumn.AllowFocus = !edit;
                }
            }

            this.grdView.Focus();

            if (edit)
            {
                string focusColumn = this.grdView.FocusedColumn.FieldName;

                if (string.IsNullOrEmpty(focusColumn))
                    focusColumn = this.COLUMN_FIRST;

                this.grdView.FocusedColumn = this.grdView.Columns[focusColumn];
                this.grdView.ShowEditor();
            }
        }

        private void SetStt()
        {
            if (this.formStatus == FormStatus.Edit)
                this.bdSource.EndEdit();

            int stt = 0;
            int length = this.grdView.RowCount;
            int index = 0;
            for (int i = 0; i < length; i++)
            {
                index = this.grdView.GetVisibleRowHandle(i);
                if (index >= 0)
                    this.grdView.SetRowCellValue(i, "STT0", ++stt);
            }
        }
        #endregion function
    }
}